import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
    Modal,
    Switch,
    KeyboardAvoidingView
} from 'react-native';

import { getImgUrl } from '../../utils/ComFunction'


import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";
import ActionSheet from 'react-native-actionsheet'
import DatePickerPart from '../../components/Tool/DatePickerPart'
import ContractAttachment from "./ContractAttachment"


const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
const screenH = Dimensions.get('window').height;
const options = ['表显里程','成交价','过户次数','钥匙数量']
const optionsValues = { '表显里程': '公里','成交价': '元','过户次数':'','钥匙数量':''  }
let addAttachments = []

let navigation

// ContractAttachment = React.createRef();
export default class FillContractPage extends Component {
    ContractAttachment = React.createRef();

    constructor(props) {
        super(props);
        this.state = {
            contractName:'',
            templateId: '',//模板id
            chooseType:'',
            fillList: [],
            customComponents:[],
            //关联车辆
            isAssociation: false,
            chooseInfos: {},

            //选择签署方
            assigns: [],
            showAssigns: false,
            selectAssigns: [],

            // fillList:[
            //     {
            //         tips:'几日内完成过户',
            //         key:'businessName',
            //         maxLength:10,
            //         type:1,
            //         value:'',
            //         id:1,
            //         isDigital:false
            //     },


            //     {
            //         tips:'车商联系电话',
            //         key:'mobile',
            //         maxLength:11,
            //         type:1,
            //         value:'',
            //         id:2,
            //         isDigital:true,
            //         formateDecial:2
            //     },

            //     {
            //         tips:'首次上牌日期',
            //         key:'year',
            //         type:2,
            //         value:'',
            //         id:3,
            //     },
            //     {
            //         tips:'备注',
            //         key:'year',
            //         type:3,
            //         value:'',
            //         id:4,
            //         lines:3
            //     },
            //     {
            //         tips:'车身颜色',
            //         key:'color',
            //         type:4,
            //         value:'',
            //         id:5,
            //         options:['黑色','白色','蓝色','红色','灰色','紫色','黄色','棕色','黑色1','白色2','蓝色3','红色4','灰色5','紫色6','黄色7','棕色8']
            //     },
            //     {
            //         tips:'车身颜色多选',
            //         key:'color',
            //         type:5,
            //         value:'',
            //         id:6,
            //         options:['黑色','白色','蓝色','红色','灰色','紫色','黄色']
            //     },

            //     {
            //         tips:'请输入公里数',
            //         key:'mileage',
            //         maxLength:10,
            //         type:1,
            //         value:'',
            //         id:7,
            //         isDigital:false,

            //     },


            // ],


            //通用日期选择相关
            dateChooseItem: [],
            consumeDate: '',
            showDatePicker: false,

            //通用的单选框相关
            chooseOptionsRadio: [],
            radioChooseItem: [],

            //通用的多选框相关
            showChecksRadios: false,
            chooseOptionsChecksRadios: [],
            checksRadioChooseItem: [],
            checksAlreadyItems: [],
            checksAlreadyItemsIds: [],

            templateName: '',//合同模板名称
            maintenanceRecordPdf: '',//维保报告PDF
            detectionReportPdf: '',//检测报告PDF
            attachmentFileList: [],//合同附件
            localImgList: [],//合同图片
        }
    }

    componentWillUnmount() {
        if (this.selectCarResultListener) {
            this.selectCarResultListener.remove();
        }
    }

    componentDidMount() {



        addAttachments = []

        if (this.props.route.params.templateList) {
            let templist = JSON.parse(this.props.route.params.templateList)

            let fileObj = {
                participantFlag: '合同附件',
                components: [

                ]
            }
            templist.push(fileObj)
            let id = this.props.route.params.templateId
            let contractNames=this.props.route.params.contractName
            let name = this.props.route.params.templateName
            let choose = this.props.route.params.chooseType
            let customComponentstemp = JSON.parse(this.props.route.params.customComponents)
            this.setState({
                fillList: templist,
                templateId: id,
                templateName: name,
                contractName:contractNames,
                customComponents:customComponentstemp,
                chooseType:choose
            }, function () {
                let assignsTemp = []
                for (let i = 0; i < this.state.fillList.length; i++) {
                    let temp = this.state.fillList[i]

                    //添加筛选签署方的字段
                    if (temp.participantFlag != '合同附件') {
                        assignsTemp.push(temp.participantFlag)
                    }


                    // let components= temp.components
                    // for(let j = 0;j < components.length;j++){
                    // console.log('=========================='+j.toString())
                    //     console.log(components[j])
                    //    }
                }
                assignsTemp.push('确认')

                //筛选签署方赋值
                this.setState({
                    assigns: assignsTemp,
                    selectAssigns: assignsTemp
                })
            })

        }

        this.selectCarResultListener = DeviceEventEmitter.addListener('selectCarResultListener', (result) => {
            //选择车辆回调
            this.setState({
                isAssociation: true,
                chooseInfos: result
            }, function () {
                this.getCarDetails(result.carId)
            })

        })

    }

    //获取车辆详情
    getCarDetails(carId) {
        let param = {
            carId: carId
        }

        HttpUtils.getRequest(HttpUrls.getOwnCarDetails, param)
            .then((result) => {
                // console.log(result)
                // console.log('============>>>>>>>>112233333')
                // // console.log(this.state.fillList)
             
                // for (let i = 0; i < this.state.customComponents.length; i++) {
                //     console.log('componentId:'+this.state.customComponents[i].componentId)
                //     console.log('customBizNum:'+this.state.customComponents[i].customBizNum)
                // }
                // console.log('============>>>>>>>>4444444')

                // for (let i = 0; i < this.state.fillList.length; i++) {
                //     let temp= this.state.fillList[i].components
                //     for(let j = 0; j < temp.length; j++){
                //     console.log('originCustomComponentId:'+temp[j].originCustomComponentId)
                //     console.log('componentName:'+temp[j].componentName)
                // }
            // }


                //这是车辆的属性和值
                Object.entries(result.data).forEach(([key, value]) => {

                    // console.log(key)
                    // console.log(value)

                if(value && value !=null ){
                    for (let i = 0; i < this.state.fillList.length; i++) {
                        let temp= this.state.fillList[i].components
                        for(let j = 0; j < temp.length; j++){
                            let finalcomponents = temp[j]
                            for(let k = 0; k < this.state.customComponents.length; k++){
                                let biztemp=this.state.customComponents[k]
                                if(finalcomponents.originCustomComponentId == biztemp.componentId){
                                    finalcomponents.customKey=biztemp.customBizNum
                                    // console.log(finalcomponents.customKey)
                                    break
                                }
                            }
                            // console.log('============>>>>>>>>')
                            // console.log(finalcomponents)
                            // console.log(finalcomponents)
                            // if(key == temp[j].componentKey){
                            //     this.refreshData(temp,value)
                            // }
    
                            //  车辆名称
                            if(key == 'carName' && finalcomponents.customKey == 'carName'){
                          
                                this.refreshData(finalcomponents,value.replace(/#/g, ' '))
                            }
    
                            //  车架号
                            else if(key == 'vcode' && finalcomponents.customKey == 'vcode'){
                                this.refreshData(finalcomponents,value.toUpperCase())
                            }
                            // 车牌号
                            else if(key == 'plateNumber' && finalcomponents.customKey == 'plateNumber'){
                                this.refreshData(finalcomponents,value)
                            }
                            // 首次上牌日期
                            else if(key == 'registerDate' && finalcomponents.customKey == 'registerDate'){
                                this.refreshData(finalcomponents,value)
                            }   
                            // 保险到期
                            else if(key == 'insuranceDate' && finalcomponents.customKey == 'insuranceDate'){
                                this.refreshData(finalcomponents,value)
                            }
                            // 年检到期
                            else if(key == 'annualInspectionDate' && finalcomponents.customKey == 'annualInspectionDate'){
                                this.refreshData(finalcomponents,value)
                            }
                            //表显里程
                            else if(key == 'mileage' && finalcomponents.customKey == 'mileage'){
                                this.refreshData(finalcomponents,(parseFloat(value)/1).toFixed(0))
                            }
                            // 外观颜色
                            else if(key == 'color' && finalcomponents.customKey == 'outerColor'){
                                if (Array.isArray(value)) {
                                    value.forEach((item) => {
                                
                                    let optionOrder=0
                                    for(let k = 0; k < finalcomponents.componentSpecialAttribute.options.length; k++){
                                        if(item.outerColor == finalcomponents.componentSpecialAttribute.options[k].optionContent){
                                            optionOrder=finalcomponents.componentSpecialAttribute.options[k].optionOrder
                                            break
                                        }
                                    }
                              
                                 this.refreshData(finalcomponents,item.outerColor,optionOrder)
                            })
                             }
                             
                            }
                            // 内饰颜色
                            else if(key == 'color' && finalcomponents.customKey == 'innerColor'){
                             
                                if (Array.isArray(value)) {
                                    value.forEach((item) => {
                                        let optionOrder=0
                                        for(let k = 0; k < finalcomponents.componentSpecialAttribute.options.length; k++){
                                            if(item.outerColor == finalcomponents.componentSpecialAttribute.options[k].optionContent){
                                                optionOrder=finalcomponents.componentSpecialAttribute.options[k].optionOrder
                                                break
                                            }
                                        }
                                        console.log(typeof(optionOrder))
                                 this.refreshData(finalcomponents,item.innerColor,optionOrder)
                               
                            })
                            }
                        }      
                            // 过户次数
                            else if(key == 'transferTimes' && finalcomponents.customKey == 'transferTimes'){
                           
                                this.refreshData(finalcomponents,value.toString())
                            }
                            // 钥匙数量
                            else if(key == 'keyNum' && finalcomponents.customKey == 'keyNum'){
                                this.refreshData(finalcomponents,value.toString())
                            }
                        
                            // else if(key == 'buyerRemark' && finalcomponents.customKey == 'buyerRemark'){
                            //     this.refreshData(finalcomponents,value)
                            // }
                            // else if(key == 'tradePrice' && finalcomponents.customKey == 'tradePrice'){
                            //     this.refreshData(finalcomponents,value)
                            // }
    
                        }
                    }
                }
              

                //     console.log(key)
                //     if (Array.isArray(value)) {
                //         value.forEach((item) => {
                //             console.log(item);
                //         });
                //     }else{
                //         console.log(value)
                //     }
                });


         

                let maintenanceRecordPdf = ''
                if (result.data.maintenanceRecord) {
                    maintenanceRecordPdf = result.data.maintenanceRecord.reportPdf
                }
                this.setState({
                    detectionReportPdf: result.data.detectionReportPdf,
                    maintenanceRecordPdf: maintenanceRecordPdf
                })

            })
            .catch((error) => {

            });
    }

    getbindcar(){
        // console.log('getbindcargetbindcar')
        // console.log(this.state.chooseType)
        if(this.state.chooseType !=2){
            if(this.state.isAssociation ){
                return (
                    <View style={styles.chooseAssociationContainer}>
                    <View style={styles.chooseTop}>
                        <Text style={styles.topTitle}>关联车辆</Text>
                        {/* 切换 */}
                        <TouchableOpacity
                            style={styles.changeContainer}
                            activeOpacity={0.8}
                            onPress={this.toassociation.bind(this)}
                        >
                            <Text style={styles.changeText}>切换</Text>
                        </TouchableOpacity>
                    </View>



                    {/* 车辆相关信息 */}
                    <View style={styles.carInfosContainer}>
                        <Image style={styles.carImg} source={{ uri: getImgUrl(this.state.chooseInfos.mainPic) }}></Image>
                        <View style={styles.carInfosRight}>
                            <Text style={styles.carTitle}
                                numberOfLines={2}
                                ellipsizeMode="tail"
                            >
                                {this.state.chooseInfos.carTitle}
                            </Text>
                            <Text style={styles.carvin}>
                                VIN：{this.state.chooseInfos.Vcode ? this.state.chooseInfos.Vcode.toUpperCase() : '未填写'}
                            </Text>
                            <Text style={styles.carprice}>
                                展厅价： {this.state.chooseInfos.carPrice}
                            </Text>
                        </View>
                    </View>

                </View>
                )
            }else{
                return(
                <View style={styles.associationContainer}>
                <Text style={styles.associationTitle}>关联销售车辆/订单</Text>
                <Text style={styles.associationTips}>自动填写关联信息，避免人为输入错误</Text>
                <TouchableOpacity
                    style={styles.toassociation}
                    activeOpacity={0.8}
                    onPress={this.toassociation.bind(this)}
                >
                    <Text style={styles.toassociationTitle}>去关联</Text>
                </TouchableOpacity>
            </View>
                )
            }
        
        }else{
            return null
        }
    }

    render() {
        navigation = this.props.navigation
        return (
            <KeyboardAvoidingView
                style={styles.container}
            >
                {/* <View style={styles.container}> */}
                <Header navigation={navigation} Title={'填写合同'} />
                {/* 选择关联车辆或者订单 */}
                {this.getbindcar()}
               
                {/* 合同信息 */}
                <View style={styles.contractInfomationContainer}>
                    <Text style={styles.contractInfomation}>合同信息</Text>
                    <TouchableOpacity
                        style={styles.contractInfomationRight}
                        activeOpacity={0.8}
                        onPress={this.choosesigns.bind(this)}
                    >
                        <Text style={styles.contractInfomationTips}>选择签署方填写项</Text>
                        <Image source={require('source/image/electron/contractchooseadd.png')} style={styles.contractInfomationImg} />
                    </TouchableOpacity>
                    <View style={styles.borderBottom} >
                    </View>
                </View>


                <FlatList
                    data={this.state.fillList}
                    renderItem={({ item, index }) => this.getItemRender(item, index)}
                    extraData={this.state}
                // ListFooterComponent={this.renderFooter.bind(this)}
                />


                {/* 底部的上一步和预览确认按钮 */}
                <View style={[styles.bottomContainer, { bottom: Constant.isIPhoneX ? Constant.bottomHeight : 0 }]}>
                    {/* 上一步 */}
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.beforePress.bind(this)}
                    >
                        <View style={styles.beforeContainer}>
                            <Text style={styles.beforeTitle}>上一步</Text>
                        </View>
                    </TouchableOpacity>
                    {/* 预览确认 */}
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.afterPress.bind(this)}
                    >
                        <View style={styles.afterContainer}>
                            <Text style={styles.beforeTitle}>预览确认</Text>
                        </View>
                    </TouchableOpacity>
                </View>

                {
                        Constant.isIPhoneX ?
                        <View style={{width: '100%', position: 'absolute', bottom: 0, backgroundColor: '#fff', height:34}}/>
                        :
                        null
                    }
                
               
                {/* <ActionSheet
                        ref={o => this.ActionSheet = o}
                        options={['车辆',  '订单', '取消']}
                        cancelButtonIndex={2}
                        
                        onPress={(index) => { this.selectAssociation(index) }}
                    /> */}

                {/* 选择签署方 */}
                {
                    this.state.showAssigns
                        ?
                        <View style={styles.containerAssign}>
                            <TouchableOpacity
                                style={styles.closeContainer}
                                activeOpacity={0.8}
                                onPress={this.closeContainer.bind(this)}
                            >
                                <View></View>

                            </TouchableOpacity>
                            <View style={[styles.modalContainer, {}]}>
                                {this.state.assigns.map(item => (
                                    <TouchableOpacity
                                        key={item}
                                        style={[styles.assignItem]}
                                        onPress={this.choosesignsItem.bind(this, item)}
                                    >
                                        <Text style={item == '确认' ? styles.itemTextConfirm : styles.itemText}>{item}</Text>
                                        {
                                            this.state.selectAssigns.includes(item) && item != '确认'
                                                ?
                                                <Image source={require('source/image/electron/assignchecked.png')} style={styles.assignChecked} />
                                                :
                                                null
                                        }
                                        <View style={styles.borderBottom} >
                                        </View>
                                    </TouchableOpacity>
                                ))}

                                {
                                    Constant.isIPhoneX ?
                                    <View style={{width: '100%', height:34}}/>
                                    :
                                    null
                                }


                            </View>                            
                        </View>
                        :
                        null
                }
                {/* 通用日期选择 */}
                <DatePickerPart
                    type={'YYYY-MM-dd'}
                    defaultDate={this.state.consumeDate} show={this.state.showDatePicker} changeState={
                        (val) => { // 时间选择组件显示与否
                            this.setState({
                                showDatePicker: val
                            })
                        }
                    } changeDate={(date) => {
                        this.refreshData(this.state.dateChooseItem, date)
                    }} />

                {/* 通用的单选框 */}
                <ActionSheet
                    ref={o => this.ActionSheetCommon = o}
                    // options={this.state.chooseOptionsRadio}
                    options={this.state.chooseOptionsRadio.map(option => option.optionContent)}

                    cancelButtonIndex={this.state.chooseOptionsRadio.length - 1}
                    onPress={(index) => { this.selectCommonOption(index) }}
                />
                {/* 通用的多选框 */}
                {
                    this.state.showChecksRadios
                        ?
                        <View style={styles.containerAssign}>
                            <TouchableOpacity
                                style={styles.closeContainer}
                                activeOpacity={0.8}
                                onPress={this.closeContainer.bind(this)}
                            >
                                <View></View>

                            </TouchableOpacity>
                            <ScrollView style={styles.choosemodalContainer}>
                                {this.state.chooseOptionsChecksRadios.map((item, index) => (
                                    <TouchableOpacity
                                        key={index}
                                        style={[styles.assignItem]}
                                        onPress={this.chooseCheckRadiosItem.bind(this, item.optionContent, item.optionOrder)}
                                    >
                                        <Text style={item == '确认' ? styles.itemTextConfirm : styles.itemText}>{item.optionContent}</Text>
                                        {
                                            this.state.checksAlreadyItems.includes(item.optionContent)
                                                ?
                                                <Image source={require('source/image/electron/assignchecked.png')} style={styles.assignChecked} />
                                                :
                                                null
                                        }
                                        <View style={styles.borderBottom} >
                                        </View>
                                    </TouchableOpacity>
                                ))}

                                {
                                    Constant.isIPhoneX ?
                                    <View style={{width: '100%', height:34}}/>
                                    :
                                    null
                                }

                            </ScrollView>

                        </View>
                        :
                        null
                }
                <Loading onRef={(ref) => (this.Loading = ref)} />
            </KeyboardAvoidingView>
        )
    }

    renderFooter() {
        return (
            <View style={{ marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 90 : 90, backgroundColor: 'white', marginTop: 10 }}>
                <ContractAttachment
                    navigation={navigation}
                    ref={this.ContractAttachment}
                    carId={this.state.chooseInfos.carId}
                    maintenanceRecordPdf={this.state.maintenanceRecordPdf}
                    detectionReportPdf={this.state.detectionReportPdf}
                    isOnlyShow={false}>

                </ContractAttachment>
            </View>
        )
    }


    //去关联
    toassociation() {
        // if (this.ActionSheet) {
        //     this.ActionSheet.show()
        // }
        //去选择车辆
        try {
            AndroidModule.selectCar({type:"2"})
        } catch (error) {
            
        }
    }

    //选择签署方
    choosesigns() {
        this.setState({
            showAssigns: true
        })
    }

    //关闭签署方
    closeContainer() {
        this.setState({
            showAssigns: false,
            showChecksRadios: false,
            checksAlreadyItems: [],
            checksAlreadyItemsIds: [],
        })
    }

    //选择的签署方
    choosesignsItem(itemTitle) {

        if (itemTitle == '确认') {
            this.setState({
                showAssigns: false
            })
            return
        }

        let temp = this.state.selectAssigns
        if (!temp.includes(itemTitle)) {
            temp.push(itemTitle)
        } else {
            temp = temp.filter(item => item !== itemTitle);
        }

        this.setState({
            selectAssigns: temp
        }, function () {
            console.log(this.state.selectAssigns)
        })


    }

    beforePress() {
        navigation.goBack()
    }



    async getAttachmentFiles() {
        if (this.ContractAttachment && this.ContractAttachment.current) {
            let result = this.ContractAttachment.current.getAttachmentFiles()
            this.setState({
                attachmentFileList: result.attachmentFileList,
                localImgList: result.localImgList
            })
            console.log('result', result)
            let templateName = this.state.templateName
            let attachmentFileList = result.attachmentFileList
            let localImgList = result.localImgList

            if (attachmentFileList.length == 0 && localImgList.length == 0) {
                return
            }

            this.Loading.show()
            let uploadIndex = 0
            for (let i = 0; i < attachmentFileList.length; i++) {
                let title = attachmentFileList[i].title

                let endWith = ''
                if (title == '维保报告' || title == '检测报告') {
                    endWith = '.pdf'
                } else {
                    endWith = '.jpg'
                }

                for (let j = 0; j < attachmentFileList[i].value.length; j++) {
                    uploadIndex = uploadIndex + 1


                    let fileUrl = getImgUrl(attachmentFileList[i].value[j])
                    let fileName = templateName + '_' + title + '_' + uploadIndex + endWith
                    await this.uploadFiles(fileUrl, fileName, uploadIndex)
                }

            }

            for (let i = 0; i < localImgList.length; i++) {
                uploadIndex = uploadIndex + 1
                let fileUrl = getImgUrl(localImgList[i])
                let fileName = templateName + '_' + '本地图片_' + uploadIndex + '.jpg'
                await this.uploadFiles(fileUrl, fileName, uploadIndex)
            }

            this.Loading.hide()

            //上传完附件后的操作
        }
    }


    /**
* 上传附件文件
* @param {*} attachmentFileList
*/
    async uploadFiles(fileUrl, fileName, index) {
        let param = {
            fileUrl: fileUrl,
            fileName: fileName
        }
        const response = await HttpUtils.postRequest(HttpUrls.esignUploadFile, param)
        console.log('response', response)
        if (response.success) {

            addAttachments.push(response.data)
        }
    }


    async afterPress() {

        // if (!this.state.chooseInfos.carId) {
        //     ToastToUser('请先选择关联车辆')
        //     return
        // }

        for (let i = 0; i < this.state.fillList.length; i++) {
            let temp = this.state.fillList[i]
            let components = temp.components
            for (let j = 0; j < components.length; j++) {
                let finalcomponents = components[j]
                if ((finalcomponents.componentType != 6 && finalcomponents.componentType != 11) && finalcomponents.required && !finalcomponents.value) {
                    ToastToUser(temp.participantFlag + '的' + finalcomponents.componentName + '为必填项')
                    return
                }
            }
        }

        await this.getAttachmentFiles()

        let participants = []

        for (let i = 0; i < this.state.fillList.length; i++) {
            let model = this.state.fillList[i]
            if (model.participantFlag != '合同附件') {
                let item = {}
                item.participantId = model.participantId
                item.participantType = model.participantType
                item.participantSetMode = model.participantSetMode
                item.participantFlag = model.participantFlag
                if (model.participantType == 1) {
                    item.orgName = model.orgParticipant.orgName
                    item.transactorPsnAccount = model.orgParticipant.transactor.transactorPsnAccount
                    item.transactorName = model.orgParticipant.transactor.transactorName
                } else {
                    item.psnAccount = model.psnParticipant.psnAccount
                    item.psnName = model.psnParticipant.psnName
                }
                participants.push(item)
            }

        }

        let arrComponents = []
        for (let i = 0; i < this.state.fillList.length; i++) {
            let model = this.state.fillList[i]
            if (model.participantFlag != '合同附件') {
                let components = model.components
                let first = 0
                for (let j = 0; j < components.length; j++) {
                    let item = {}
                    if (components[j].componentType == 6 || components[j].componentType == 11) {
                        continue
                    }
                    item.participantFlag = model.participantFlag
                    item.showIndex = first
                    first += 1
                    item.fileId = components[j].fileId
                    item.componentId = components[j].componentId
                    item.componentValue = components[j].value
                    item.componentName = components[j].componentName
                    if (components[j].componentType == 9 || components[j].componentType == 10 || components[j].componentType == 14) {
                        item.componentValue = components[j].optionOrder
                        item.componentValueShow = components[j].value
                    }
                    arrComponents.push(item)
                }
            }

        }



        // const myMap = new Map([
        //     ['mainPic', this.state.chooseInfos.mainPic],
        //     ['vcode',this.state.chooseInfos.Vcode],
        //     ['carName', this.state.chooseInfos.carTitle],
        //   ]);
        //   const mapEntries = [...myMap].map(([key, value]) => `${key}:${value}`);
        //   const mapAsString = mapEntries.join(',');

        let carInfos = {
            'carName': this.state.chooseInfos.carTitle,
            'vcode': this.state.chooseInfos.Vcode,
            'mainPic': this.state.chooseInfos.mainPic
        }

        let param = {
            components: arrComponents,
            participants: participants,
            templateId: this.state.templateId,
            bizId: this.state.chooseInfos?this.state.chooseInfos.carId:'',
            bizType: this.state.chooseInfos?1:'',
            operator: Constant.fullName ? Constant.fullName : Constant.userId,
            merchantId: Constant.merchantId,
            bizInfo: JSON.stringify(carInfos),
            addAttachments: addAttachments,
            contractName:this.state.contractName
        }
        console.log(param)

        if (this.Loading) {
            this.Loading.show();
        }


        HttpUtils.postRequest(HttpUrls.contractProdcreate, param)
            .then((result) => {
                console.log(result)
                if (this.Loading) {
                    this.Loading.hide();
                }

                let code = result.code
                if (code == 0) {
                    let params = {
                        components: JSON.stringify(arrComponents),
                        participants: JSON.stringify(participants),
                        contractNo: result.data.contractNo,
                        attachmentFileList: JSON.stringify(this.state.attachmentFileList),
                        localImgList: JSON.stringify(this.state.localImgList)
                    }
                    navigation.navigate('ConfirmInfosPage',params)
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {

            });


        // this.getAttachmentFiles()


    }

    getItemRender(item, index) {
        if (!this.state.selectAssigns.includes(item.participantFlag)) {

            if (item.participantFlag == '合同附件') {
                return (
                    <View style={{ marginBottom: Constant.isIPhoneX ? Constant.bottomHeight + 90 : 90, backgroundColor: 'white', marginTop: 10 }}>
                        <ContractAttachment
                            ref={this.ContractAttachment}
                            carId={this.state.chooseInfos.carId}
                            maintenanceRecordPdf={this.state.maintenanceRecordPdf}
                            detectionReportPdf={this.state.detectionReportPdf}
                            isOnlyShow={false}>

                        </ContractAttachment>
                    </View>
                )
            } else {
                return null
            }


        } else {
            return (
                <View key={item.participantId}>
                    <View style={styles.contractInfomationContainer}>
                        <Text style={styles.contractInfomation}>{item.participantFlag}</Text>
                        <View style={styles.borderBottom} >
                        </View>
                    </View>

                    {item.components.map((itemFinal, indexFinal) => (
                        this.getItemFinal(itemFinal, indexFinal, item.components.length)
                    ))}
                </View>
            );

        }

    }

    getItemFinal(item, index, itemlength) {
        let extraContent;
        switch (item.componentType) {
            //单行文本或者数字
            case 1:
            case 2:
            case 19:
            case 16:
                const keyboardType = (item.componentType == 2 || item.componentType == 19 ) ? 'numeric' : 'default';
                let maxLength = 15
                // console.log(item)
                if (item.componentType == 19) {
                    maxLength = 11
                } else if (item.componentType == 16) {
                    maxLength = 18
                } else if (item.componentSpecialAttribute.componentMaxLength) {
                    maxLength = parseInt(item.componentSpecialAttribute.componentMaxLength)
                }
                extraContent = (
                    <View style={[styles.commonItem]} key={item.componentId}>
                        <Text style={styles.extraKey}>{item.componentName}
                            {
                                item.required
                                    ?
                                    <Text style={{ marginLeft: 5, color: 'red' }}> *</Text>
                                    :
                                    null
                            }
                        </Text>

                        <TextInput
                            editable={true}
                            style={styles.commoninputbox}
                            placeholder='请输入'
                            placeholderTextColor={'#999999'}
                            maxLength={maxLength}
                            keyboardType={keyboardType}
                            value={item.value}
                            onChangeText={this.onChangeTemplateInfo.bind(this, item)}
                        ></TextInput>
                        <View style={styles.inputCountContainer}>
                            {
                                options.includes(item.componentName)
                                    ?
                                    <Text style={styles.inputCount}>{optionsValues[item.componentName]}</Text>
                                    :
                                    <Text style={styles.inputCount}>{item.count ? item.count + '/' + maxLength : '0/' + maxLength}</Text>
                            }
                        </View>
                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }

                    </View>
                );
                break;
            //多行文本
            case 8:
                const lines = item.lines ? item.lines : 3
                extraContent = (
                    <View style={[styles.textAreaContainer, { height: 30 * lines }]} key={item.id}>
                        <TextInput
                            style={[styles.teatArea, { height: 30 * lines }]}
                            placeholder={item.componentName}
                            placeholderTextColor={'#999999'}
                            value={item.value}
                            numberOfLines={lines}
                            onChangeText={this.onChangeTemplateInfo.bind(this, item)}
                            multiline={true}
                            textAlignVertical="top"
                        ></TextInput>

                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }
                    </View>

                )
                break;

            //日期
            case 3:
                extraContent = (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.selectData.bind(this, item)}>
                        <View style={[styles.commonItem]} key={item.componentId}>
                            <Text style={styles.extraKey}>{item.componentName}

                                {
                                    item.required
                                        ?
                                        <Text style={{ marginLeft: 5, color: 'red' }}> *</Text>
                                        :
                                        null
                                }
                            </Text>
                            <Text style={item.value ? styles.extraValue : styles.extraValuePlaceHoder}>{item.value ? item.value : '请选择'}</Text>

                        </View>
                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }
                    </TouchableOpacity>
                )

                break;

            //单选
            case 10:
            case 14:
                extraContent = (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.selectRadio.bind(this, item)}>
                        <View style={[styles.commonItem]} key={item.componentId}>
                            <Text style={styles.extraKey}>{item.componentName}

                                {
                                    item.required
                                        ?
                                        <Text style={{ marginLeft: 5, color: 'red' }}> *</Text>
                                        :
                                        null
                                }
                            </Text>
                            <Text style={item.value ? styles.extraValue : styles.extraValuePlaceHoder}>{item.value ? item.value : '请选择'}</Text>
                        </View>
                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }
                    </TouchableOpacity>
                )
                break;


            //多选
            case 9:
                extraContent = (
                    <TouchableOpacity
                        activeOpacity={0.8}
                        onPress={this.selectCheckRadios.bind(this, item)}
                    >
                        <View style={[styles.commonItem]} key={item.componentId}>
                            <Text style={styles.extraKey}>{item.componentName}
                                {
                                    item.required
                                        ?
                                        <Text style={{ marginLeft: 5, color: 'red' }}> *</Text>
                                        :
                                        null
                                }
                            </Text>
                            <Text style={item.value ? styles.extraValue : styles.extraValuePlaceHoder}>{item.value ? item.value : '请选择'}</Text>
                        </View>
                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }
                    </TouchableOpacity>
                )
                break;
            //勾选
            case 15:
                extraContent = (
                    <View>
                        <View style={[styles.commonItem]} key={item.componentId}>
                            <Text style={styles.extraKey}>{item.componentName}
                                {
                                    item.required
                                        ?
                                        <Text style={{ marginLeft: 5, color: 'red' }}> *</Text>
                                        :
                                        null
                                }
                            </Text>
                            <TouchableOpacity
                                activeOpacity={0.8}
                                onPress={this.selectSwitch.bind(this, item)}
                            >
                                {
                                    item.value
                                        ?
                                        <Image source={require('source/image/electron/selected.png')} style={styles.selected} />
                                        :
                                        <Image source={require('source/image/electron/unselected.png')} style={styles.selected} />
                                }

                            </TouchableOpacity>
                        </View>
                        {
                            index != itemlength - 1
                                ?
                                <View style={styles.borderBottom} >
                                </View>
                                :
                                null
                        }
                    </View>
                )
                break;


            default:
                extraContent = null
        }

        return (
            <View>
                {extraContent}
            </View>

        );
    }

    onChangeTemplateInfo = (chooseItem, value) => {

        // if(chooseItem.isDigital && chooseItem.formateDecial){
        //     const regex = new RegExp(`^-?\\d*(\\.\\d{0,${chooseItem.formateDecial}})?$`);
        //     if(!regex.test(value)){
        //         const parts = value.split('.');
        //         console.log(parts)
        //         if (parts.length > 1) {
        //           // 如果有小数点，保留 a 位
        //           parts[1] = parts[1].slice(0, chooseItem.formateDecial); // 截取小数部分
        //           value=parts.join('.')
        //           console.log(value)
        //         }
        //     }
        // }
        // console.log(chooseItem)
        // console.log(value)
        // console.log(typeof(value))
        this.refreshData(chooseItem, value)


    }

    selectSwitch(item) {
        let temp = item.value
        if (temp == 1) {
            temp = 0
        }
        else {
            temp = 1
        }
        this.refreshData(item, temp)
    }

    //刷新数据
    refreshData(chooseItem, value, optionOrder) {
        // if(chooseItem.componentName=='过户次数'){
        //     console.log('======>>>>>>>>>>>2222222222')
        //     console.log(chooseItem.componentId)
        // }
        const newFillList = this.state.fillList.map(item => {
          
            const newComponents = item.components.map(component => {
                if (component.componentId === chooseItem.componentId) {
                    
                    // if(component.componentId == '892723a2405945f7b8c987a75dfc7ea4'){
                    //     console.log(component)
                   
                    // }
                    return { ...component, count: value.length?value.length:0, value: value, optionOrder: optionOrder };
                }
                return component;
            });
            return { ...item, components: newComponents };
        });

        //   for(let i = 0;i < newFillList.length;i++){
        //         let temp = newFillList[i]
        //         for(let j = 0;j < temp.components.length;j++){
        //             console.log(temp.components[j])
        //         }
        //   }

        this.setState({
            fillList: newFillList
        })
    }

    //日期选择
    selectData(item) {
        this.setState({
            dateChooseItem: item,
            showDatePicker: true,
            consumeDate: item.value
        })

    }

    //单选选择
    selectRadio(item) {

        const options = [...item.componentSpecialAttribute.options, { optionContent: '取消' }];

        this.setState({
            chooseOptionsRadio: options,
            radioChooseItem: item
        }, function(){
            if (this.ActionSheetCommon) {
                this.ActionSheetCommon.show()
            }
        })
    }

    //单选选择
    selectCommonOption(index) {
        const selectedOption = this.state.chooseOptionsRadio[index]; // 通过索引获取完整对象
        if (selectedOption.optionContent == '取消') {
            return
        }
        // console.log(typeof(selectedOption.optionOrder))
        this.refreshData(this.state.radioChooseItem, selectedOption.optionContent, selectedOption.optionOrder)
       
    }


    //多选选择
    selectCheckRadios(item) {
        const options = [...item.componentSpecialAttribute.options, { optionContent: '确认' }];
        this.setState({
            showChecksRadios: true,
            chooseOptionsChecksRadios: options,
            checksRadioChooseItem: item,
            checksAlreadyItems: item.value ? item.value.split(',') : [],
            checksAlreadyItemsIds: item.optionOrder ? item.optionOrder.split(',') : []
        })
    }

    //多选
    chooseCheckRadiosItem(itemTitle, optionOrder) {

        if (itemTitle == '确认') {
            this.setState({
                showChecksRadios: false
            })
            let alreadyChoose = ''
            for (let i = 0; i < this.state.checksAlreadyItems.length; i++) {
                if (i == this.state.checksAlreadyItems.length - 1) {
                    alreadyChoose += this.state.checksAlreadyItems[i]
                } else {
                    alreadyChoose += this.state.checksAlreadyItems[i] + ','
                }

            }

            let alreadyChooseIds = ''
            for (let i = 0; i < this.state.checksAlreadyItemsIds.length; i++) {
                if (i == this.state.checksAlreadyItemsIds.length - 1) {
                    alreadyChooseIds += this.state.checksAlreadyItemsIds[i]
                } else {
                    alreadyChooseIds += this.state.checksAlreadyItemsIds[i] + ','
                }

            }




            this.refreshData(this.state.checksRadioChooseItem, alreadyChoose, alreadyChooseIds)
            return
        }


        let temp = this.state.checksAlreadyItems
        let tempIds = this.state.checksAlreadyItemsIds

        if (temp == '') {
            temp = []
            tempIds = []
        }
        if (!temp.includes(itemTitle)) {
            temp.push(itemTitle)
            tempIds.push(optionOrder)
        } else {
            temp = temp.filter(item => item !== itemTitle);
            tempIds = tempIds.filter(item => item !== optionOrder);
        }

        this.setState({
            checksAlreadyItems: temp,
            checksAlreadyItemsIds: tempIds
        })




    }


}

const styles = StyleSheet.create({

    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#f6f6f6'
    },

    associationContainer: {
        height: 72,
        width: screenW,
        marginTop: 10,
        backgroundColor: '#ffffff'
    },

    associationTitle: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
        marginTop: 13,
        marginLeft: 16
    },

    associationTips: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        marginTop: 4,
        marginLeft: 16
    },

    toassociation: {
        position: 'absolute',
        width: 74,
        height: 26,
        borderRadius: 4,
        borderColor: '#E5E5E5',
        borderWidth: 0.5,
        right: 16,
        top: 12,
        alignItems: 'center',
        justifyContent: 'center',
    },

    toassociationTitle: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    chooseAssociationContainer: {
        height: 150,
        width: screenW,
        backgroundColor: '#ffffff',
        marginTop: 10
    },

    chooseTop: {
        height: 48,
        alignItems: 'center',
        flexDirection: 'row',
    },

    topTitle: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
        marginLeft: 16
    },

    changeContainer: {
        position: 'absolute',
        right: 16,
        alignItems: 'center',
        justifyContent: 'center'
    },

    changeText: {
        fontWeight: '400',
        fontSize: 14,
        color: '#F99802',
    },

    carInfosContainer: {
        height: 102,
        flexDirection: 'row'
    },

    carImg: {
        width: 130,
        height: 90,
        marginLeft: 16,
        borderRadius: 4
    },

    carInfosRight: {
        width: screenW - 32 - 12 - 130,
        marginLeft: 12,
        marginRight: 16
    },

    carTitle: {
        fontWeight: '500',
        fontSize: 14,
        color: '#333333',
        height: 40,
        lineHeight: 20
    },

    carvin: {
        fontWeight: '400',
        fontSize: 12,
        color: '#333333',
        marginTop: 4
    },

    carprice: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginTop: 9
    },

    contractInfomationContainer: {
        height: 48,
        marginTop: 10,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row'
    },


    contractInfomation: {
        fontWeight: '500',
        fontSize: 16,
        color: '#333333',
        marginLeft: 16
    },

    contractInfomationRight: {
        flexDirection: 'row',
        height: 48,
        position: 'absolute',
        right: 16,
        alignItems: 'center'
    },

    contractInfomationTips: {
        fontWeight: '400',
        fontSize: 14,
        color: '#666666',
    },

    contractInfomationImg: {
        width: 25,
        height: 25,
        marginLeft: 7
    },


      containerAssign: {
        width:screenW,
        height:screenH,
        backgroundColor:'rgba(0, 0, 0, 0.4)',
        zIndex: 1000,
        position: "absolute",
        left: 0,
        bottom: 0,
    },

    closeContainer: {
        flex: 1
    },

    modalContainer: {

        width: screenW,
        backgroundColor: '#ffffff',
        position: 'absolute',
        bottom: 0
    },

    choosemodalContainer: {
        width: screenW,
        backgroundColor: '#ffffff',
        position: 'absolute',
        bottom: 0,
        maxHeight: 500
    },

    assignItem: {
        height: 45,
        alignItems: 'center',
        justifyContent: 'center',
        width: screenW,
    },

    itemText: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
    },

    itemTextConfirm: {
        fontWeight: '400',
        fontSize: 14,
        color: 'blue',
    },


    borderBottom: {
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
        position: 'absolute',
        bottom: 0,
        width: screenW,
        marginLeft: 15
    },

    assignChecked: {
        position: 'absolute',
        right: 15,
        width: 18,
        height: 18,
    },


    commonItem: {
        height: 46,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        flexDirection: 'row'
    },

    extraKey: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        marginLeft: 16,
        width: 100
    },

    extraValue: {
        fontWeight: '400',
        fontSize: 14,
        color: '#333333',
        position: 'absolute',
        marginLeft: 120
    },

    extraValuePlaceHoder: {
        fontWeight: '400',
        fontSize: 14,
        color: '#999999',
        position: 'absolute',
        marginLeft: 120
    },

    commoninputbox: {
        width: screenW - 120 - 52,
        height: 46,
        fontSize: 14,
        padding: 0,
        margin: 0,
        left: 120,
        position: 'absolute'
    },

    inputCountContainer: {
        height: 46,
        position: 'absolute',
        right: 14,
        alignItems: 'center',
        flexDirection: 'row'
    },

    inputCount: {
        fontWeight: '400',
        fontSize: 14,
        color: '#222222',
    },

    textAreaContainer: {
        backgroundColor: '#ffffff',
        width: screenW
    },

    teatArea: {
        width: screenW - 24,
        marginLeft: 12,
        marginRight: 12,
        lineHeight: 20
    },

    bottomContainer: {
        position: 'absolute',
        height: 80,
        backgroundColor: '#ffffff',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        width: screenW
    },

    beforeContainer: {
        width: 168,
        height: 48,
        backgroundColor: '#F5F5F5',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center'
    },

    beforeTitle: {
        fontWeight: '400',
        fontSize: 16,
        color: '#333333',
    },

    afterContainer: {
        width: 168,
        height: 48,
        backgroundColor: '#FFE000',
        borderRadius: 4,
        alignItems: 'center',
        justifyContent: 'center',
        marginLeft: 8
    },

    gouxuanContainer: {
        width: screenW - 110 - 52,
        height: 46,
        fontSize: 14,
        padding: 0,
        margin: 0,
        left: 110,
        position: 'absolute',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },

    selected: {
        width: 40,
        height: 25,
        marginLeft: 3
    }


})